<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <template v-slot:before>
          <span>共{{ page.total }}条记录</span>
        </template>
        <template #after>
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import')"
            >导入</el-button
          >
          <el-button size="small" type="danger" @click="exportData"
            >导出</el-button
          >
          <el-button size="small" type="primary" @click="showDialog = true"
            >新增员工</el-button
          >
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border v-loading="loading" :data="list">
          <el-table-column type="index" label="序号" sortable="" />
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column label="头像">
            <template v-slot="{ row }">
              <img
                @click="showQrCode(row.staffPhoto)"
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                alt=""
                style="
                  border-radius: 50%;
                  width: 100px;
                  height: 100px;
                  padding: 10px;
                "
              />
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column
            :formatter="formatEmployment"
            prop="formOfEmployment"
            label="聘用形式"
            sortable=""
          />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable="">
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column prop="enableState" label="账户状态" sortable="">
            <template v-slot="{ row }">
              <el-switch :value="row.enableState === 1"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
                >查看</el-button
              >
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)"
                >角色</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="deleteEmployee(row.id)"
                :disabled="!checkPermission('point-user-delete')"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="prev, pager, next"
            @current-change="changePage"
            :page-size="page.size"
            :total="page.total"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 放置弹窗层 -->
    <!-- sync修饰符 子组件改变父组件数据的一个语法糖 -->
    <AddDemployee :show-dialog.sync="showDialog" />
    <!-- 放置二维码 -->
    <el-dialog title="二维码" :visible.sync="showCodeDialog">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <!-- 放置角色弹窗 -->
    <assign-role
      :showRoleDialog.sync="showRoleDialog"
      ref="assignRole"
      :user-id="userId"
    />
  </div>
</template>

<script>
import assignRole from "./components/assign-role.vue";
import QrCode from "qrcode";
import AddDemployee from "./components/add-employee.vue";
import EmployeeEnum from "@/api/constant/employees";
import { getEmployeeList, delEmployee } from "@/api/employees";
import { formatDate } from "@/filters";
import AssignRole from "./components/assign-role.vue";
export default {
  components: {
    AddDemployee,
    assignRole,
  },
  data() {
    AssignRole;
    return {
      list: [],
      page: {
        page: 1,
        size: 10,
        total: 0,
      },
      // 显示遮罩层
      loading: false,
      showDialog: false,
      showCodeDialog: false,
      showRoleDialog: false,
      userId: null,
    };
  },
  created() {
    this.getEmployeeList();
  },
  methods: {
    async getEmployeeList() {
      this.loading = true;
      const { total, rows } = await getEmployeeList(this.page);
      this.page.total = total;
      this.list = rows;
      this.loading = false;
    },
    // 改变当前的页码
    changePage(newPage) {
      this.page.page = newPage;
      this.getEmployeeList();
    },
    // 格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
      // 要去找1对应的所有值
      const obj = EmployeeEnum.hireType.find((item) => item.id === cellValue);
      // console.log(obj);
      return obj ? obj.value : "未知";
    },
    // 删除功能
    async deleteEmployee(id) {
      try {
        await this.$confirm("你确定要删除该员工吗");
        await delEmployee(id);
        this.getEmployeeList();
        this.$message.success("删除员工成功");
      } catch (error) {
        console.log(error);
      }
    },
    // deleteEmployee(id) {
    //   this.$confirm('你确定要删除该员工吗').then(() => {
    //     delEmployee(id)
    //   }).then(() => {
    //     this.getEmployeeList()
    //     this.$message.success("删除员工成功")
    //   }).catch((error) => {
    //     console.log(error);
    //   })
    // }

    // 转换数据格式的方法
    translate(inputData = [], mapRelation = {}) {
      const header = Object.keys(mapRelation);
      return inputData.map((item) => {
        const arr = [];
        header.forEach((zhKey) => {
          const enKey = mapRelation[zhKey];
          let value = item[enKey];
          // 转换时间
          if (enKey === "timeOfEntry" || enKey === "correctionTime") {
            value = formatDate(value);
          }
          // 转换聘用形式
          if (enKey === "formOfEmployment") {
            const obj = EmployeeEnum.hireType.find((item) => item.id === value);
            value = obj ? obj.value : "未知";
          }
          arr.push(value);
        });
        return arr;
      });
    },
    // 懒加载模块  => 只有点击按钮的时候才会加载这个模块
    exportData() {
      const headers = {
        手机号: "mobile",
        姓名: "username",
        入职日期: "timeOfEntry",
        聘用形式: "formOfEmployment",
        转正日期: "correctionTime",
        工号: "workNumber",
        部门: "departmentName",
      };
      // 懒加载
      // 2.拉取模块
      import("@/vendor/Export2Excel").then(async (excel) => {
        // 3.获取数据
        const { rows } = await getEmployeeList({
          page: 1,
          size: this.page.total,
        });
        // 4.转换数据
        const data = this.translate(rows, headers);
        const header = Object.keys(headers);
        // 导出结构新增一层单元格
        const multiHeader = [["姓名", "主要信息", "", "", "", "", "部门"]];
        // 对单元格进行合并
        const merges = ["A1:A2", "B1:F1", "G1:G2"];
        // 5.执行导出
        excel.export_json_to_excel({
          fileename: "人力资源表",
          header,
          data,
          multiHeader, //复杂表头
          merges, // 合并选项
        });
      });
    },
    // 点击之后显示出二维码
    showQrCode(url) {
      if (!url) {
        return this.$message.warning("该用户还未上传头像");
      }
      this.showCodeDialog = true;
      // 因为dom更新是异步操作，需要在nextTick里面执行
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.myCanvas, url);
      });
    },
    // 点击角色跳出弹窗
    async editRole(id) {
      // props传值是异步的
      this.userId = id;
      // 父组件调用子组件的方法
      await this.$refs.assignRole.getUserDetailById(id);
      this.showRoleDialog = true;
    },
  },
};
</script>

<style>
</style>
